<template>
  <el-container id="message-customer-detail">
    <el-main>
      <el-container>
        <el-header>
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/message/template' }">模版消息</el-breadcrumb-item>
              <el-breadcrumb-item>{{templateMsg.id ? '编辑消息' : '新增消息'}}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
        </el-header>
      </el-container>
      <el-form :model="templateMsg" :rules="rules" ref="templateMsg" label-width="100px" class="demo-customerMsg">
        <el-form-item label="名称" prop="pushName">
          <el-input v-model="templateMsg.pushName" placeholder="请输入名称，最大30个汉字"></el-input>
        </el-form-item>
        <el-form-item label="推送时间" prop="pushType">
          <el-col :span="6">
            <el-select value-key="value" v-model="templateMsg.pushType" placeholder="推送方式">
              <el-option label="定时推送" value="DELAY"></el-option>
              <el-option label="立即推送" value="NOW"></el-option>
            </el-select>
          </el-col>
          <el-col :span="18">
            <el-date-picker type="datetime" placeholder="选择时间" :disabled="templateMsg.pushType === 'NOW'" v-model="templateMsg.pushTime" style="width: 100%;" :picker-options="pickerOptions" @change="changeTime"></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="推送范围" prop="pushRange">
          <el-radio-group v-model="templateMsg.pushRange">
            <el-radio label="ALL">全部粉丝</el-radio>
            <el-radio label="DESIGNATED_OPEN_ID" :disabled="true">指定openId</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="消息" prop="pushContent">
          <el-input type="textarea" v-model="templateMsg.pushContent" rows="4" placeholder="请输入消息json"></el-input>
        </el-form-item>
        <el-form-item label="预览">
          <el-input v-model="openid" placeholder="请输入预览者的openid"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="submitPreview">预览</el-button>
          <el-button @click="getOpenid" type="primary" plain v-if="!isopeid">扫码获取openid</el-button>
          <div id="qrcode" ref="qrcode"></div>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm">重置</el-button>
          <el-button type="primary" @click="submitForm">保存</el-button>
        </el-form-item>
      </el-form>
    </el-main>
  </el-container>
</template>

<script>
import E from 'wangeditor';
import { mapActions, mapState } from 'vuex';
import op from 'object-path';
import _ from 'underscore';
import QrCode from './qrCode.vue';

import CONSTANT from '../../../constant/common';
import auth from '../../../util/auth';
import service from '../../../service/message';
/* eslint-disable */
const openIdsReg = /[A-Za-z0-9\-_]+/g;
let timer;
const defaultTemplateMsg = {
  id: '',
  pushName: '',
  pushTime: '',
  pushType: '',
  pushRange: 'ALL',
  pushContent: ''
};
// const TYPE_IS_EDIT = 'edit';
const TYPE_IS_ADD = 'add';

export default {
  data() {
    const validatePushTimeType = (rule, value, callback) => {
      if (value === 'DELAY' && !this.templateMsg.pushTime) {
        callback(new Error('请选择推送时间'));
      } else {
        callback();
      }
    };
    const JSONStringCheck = (rule, value, callback) => {
      if (!isJson(value)) {
        callback(new Error("请输入正确的json格式"));
      } else {
        callback();
      }
    };
    const isJson = (data) => {
      if (typeof data === 'string') {
        try {
          let obj = JSON.parse(data);
          if (typeof obj === 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          return false
        }
      }
    };
    const contentCurrent = (rule, value, callback) => {
      if(value.indexOf('template_id')<0 || value.indexOf('url')<0) {
        callback(new Error("请在消息中需要包含template_id和url信息"));
      } else {
        callback();
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      isopeid: false,
      openid: '',
      templateMsg: {...defaultTemplateMsg},
      rules: {
        pushName: [
          {required: true, message: '请输入名称', trigger: 'blur'},
          {
            max: 30, message: '请少于30个字', trigger: 'blur',
          },
        ],
        pushRange: [
          {required: true, message: '请选择推送范围', trigger: 'change'},
        ],
        pushType: [
          {required: true, message: '请选择推送方式', trigger: 'change'},
          {validator: validatePushTimeType, trigger: 'change'},
        ],
        pushContent: [
          {required: true, message: '消息不能为空', trigger: 'blur'},
          {validator: JSONStringCheck, trigger: 'blur'},
          {validator: contentCurrent, trigger: 'blur'},
        ]
      }
    };
  },
  watch: {
    editInfo(nv) {
      if (!_.isEmpty(nv)) {
        const info = nv;
        this.templateMsg = {
          id: info.id || '',
          pushName: info.pushName || '',
          pushTime: info.pushTime || '',
          pushType: info.pushType === 1 ? 'NOW' : 'DELAY',
          pushRange: info.pushRange === 1 ? 'ALL' : 'DESIGNATED_OPEN_ID',
          pushContent: info.pushContent || '',
        };
      }
    },
  },
  computed: {
    ...mapState({
      editInfo (state) {
        return state.message.templateMsgList.filter(item => item.id === this.$route.query.id)[0]
      }
    }),
    appId() {
      const localWoa = localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA) ?
        JSON.parse(localStorage.getItem(CONSTANT.STORAGE_LOCAL_WOA)) : {};
      return this.$store.state.woa.currentWoa.appId || localWoa.appId;
    },
  },
  components: {
  },
  mounted() {
    this.initTemplateMsg()
    this.initOpenid();
  },
  methods: {
    ...mapActions([
      'previewTemplateMessage',
      'uploadMpNewsMessage',
      'addTemplateMessage',
      'updateTemplateMessage',
      'getMpNewsByMediaId',
      'getImageByMediaId',
      'getVoiceByMediaId',
    ]),
    initTemplateMsg() {
      const info = this.editInfo;
      if (info) {
        // 编辑的时候，把vuex的数据存在localstorage，刷新页面也会有数据
        localStorage.setItem("templateMsg", JSON.stringify(info));
        this.setTemplateMsg(info)
      } else {
        if(this.$route.query.id && localStorage.getItem("templateMsg") && JSON.parse(localStorage.getItem("templateMsg")).id == this.$route.query.id) {
          this.setTemplateMsg(JSON.parse(localStorage.getItem("templateMsg")));
        }
      }
    },
    setTemplateMsg(info) {
      this.templateMsg = {
        id: info.id || '',
        pushName: info.pushName || '',
        pushTime: info.pushTime || '',
        pushType: info.pushType === 1 ? 'NOW' : 'DELAY',
        pushRange: info.pushRange === 1 ? 'ALL' : 'DESIGNATED_OPEN_ID',
        pushContent: info.pushContent || '',
      };
    },
    changeTime() {
      if (new Date(this.templateMsg.pushTime).getTime() < new Date().getTime()) {
        this.templateMsg.pushTime = '';
        this.$message.error('所选时间要大于当前时间');
      }
    },
    qrcode() {
      service.getQrcodeUrl({ appid: this.appId }).then((res) => {
        this.$msgbox({
          title: '扫二维码获取openid',
          showConfirmButton: false,
          message: this.$createElement(QrCode, {
            key: this.key + 1,
            props: {
              address: res,
            },
          }),
        }).catch(() => {
          if (timer) {
            clearInterval(timer);
          }
        });
      });
    },
    getOpenid() {
      this.qrcode();
      timer = setInterval(() => {
        service.getOpenid({ appid: this.appId }).then((res) => {
          if (res.openid) {
            this.openid = res.openid;
            this.$msgbox.close();
            clearInterval(timer);
            this.isopeid = true;
          }
        });
      }, 300);
      // this.$msgbox.close();
    },
    initOpenid() {
      service.getOpenid({ appid: this.appId }).then((res) => {
        if (res.openid) {
          this.openid = res.openid;
          this.isopeid = true;
        }
      });
    },
    doSave(data) {
      if (data.id) {
        this.updateTemplateMessage(data).then((res) => {
          if(res.indexOf('成功')<0){
            this.$message.error(res)
          } else {
            this.resetForm();
            this.$message({
              type: 'success',
              message: '编辑模版消息成功!',
            });
            this.$router.push({
              path: '/message/template',
            });
          }
        }, (e) => {
          this.$message({
            type: 'error',
            message: `编辑保存模版消息失败->${e.message}`,
          });
        });
      } else {
        this.addTemplateMessage(data).then((res) => {
          if(res.indexOf('成功')<0){
            this.$message.error(res)
          } else {
            this.resetForm();
            this.$message({
              type: 'success',
              message: '创建模版消息成功!',
            });
            this.$router.push({
              path: '/message/template',
            });
          }
        }, (e) => {
          this.$message({
            type: 'error',
            message: `创建模版消息失败->${e.message}`,
          });
        });
      }
    },
    submitForm() {
      const {
        id, pushName, pushRange, pushTime, pushType, pushContent,
      } = this.templateMsg;
      let $pushTime = pushTime;
      let $pushRange = 1
      const submitProcess = () => {
        if (pushRange === 'ALL') {
          $pushRange = 1
        }
        if (pushType === 'NOW') {
          $pushTime = 0;
        }
        const data = {
          pushName,
          pushTime: $pushTime ? +new Date($pushTime) : 0,
          pushType: pushType === 'NOW'?1:2,
          pushRange: $pushRange,
          pushContent,
          appid: this.appId,
          id
        };
        if (pushType === 'NOW') {
          this.$confirm('将立即群发消息给用户，请确认操作', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            center: true,
          }).then((ok) => {
            this.doSave(data);
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消',
            });
          });
        } else {
          this.doSave(data);
        }
      };
      this.$refs.templateMsg.validate().then(submitProcess);
    },
    resetForm() {
      this.templateMsg = {...defaultTemplateMsg};
    },
    isJson(data) {
      if (typeof data === 'string') {
        try {
          let obj = JSON.parse(data);
          if (typeof obj === 'object' && obj) {
            return true
          } else {
            return false
          }
        } catch (e) {
          return false
        }
      }
    },
    submitPreview() {
      const data = {
        content: this.templateMsg.pushContent,
        openId: this.openid,
        appid: this.appId,
      };
      if (!this.templateMsg.pushContent) {
        return this.$message({
          type: 'error',
          message: '请输入消息内容',
        });
      }
      if(!this.isJson(this.templateMsg.pushContent)){
        return this.$message({
          type: 'error',
          message: '请输入json格式的消息内容',
        });
      }
      if(this.templateMsg.pushContent.indexOf('template_id')<0 || this.templateMsg.pushContent.indexOf('url')<0){
        return this.$message({
          type: 'error',
          message: '请在消息中需要包含template_id和url信息',
        });
      }
      if (!this.openid) {
        return this.$message({
          type: 'error',
          message: '请输入预览者openId',
        });
      }
      return this.previewTemplateMessage(data).then((resp) => {
        console.log('resp ', resp);
        if (resp.errorCode && resp.errorCode === '1') {
          this.$message({
            type: 'error',
            message: `${resp.errorMsg || '发送预览失败，请稍后再试或者联系管理员'}`,
          });
        } else {
          this.$message({
            type: 'success',
            message: '发送预览成功',
          });
        }
      }, (e) => {
        this.$message({
          type: 'error',
          message: `发送预览失败->${e.message}`,
        });
      });
    },
  },
};
</script>

<style lang="less">
#message-customer-detail {
  .breadcrumb {
    height: 40px;
  }
  #image-word-edit, #word-edit {
    margin-bottom: 22px;
    .w-e-text-container {
      z-index: 2000 !important;
    }
  }
  .media-wap {
    margin-top: 180px;
  }
  .media-info {
    height: 102px;
    line-height: 25px;
  }
  .upload__tip {
    height: 120px;
  }
}
</style>
